package com.ucap.spyxmp.data;


import com.alibaba.fastjson.JSONObject;
import com.ucap.spyxmp.exception.ErrorCode;
import com.ucap.spyxmp.exception.GlobalErrorCode;

/**
 * 分页统一返回结果集
 */
public class PageRestResultBuilder extends RestResultBuilder {

    /** 起始索引 */
    private int start;
    /** 每页条数 */
    private int limit;
    /** 本页条数 */
    private int total;
    /** 总条数 */
    private int totalCount;

    public static PageRestResultBuilder builder() {
        PageRestResultBuilder pageRestResultBuilder = new PageRestResultBuilder();
        return pageRestResultBuilder;
    }

    public PageRestResultBuilder success(JSONObject jsonList) {
        success(jsonList.get("rows"));
        this.start = (int)jsonList.get("start");
        this.limit = (int)jsonList.get("limit");
        this.total = (int)jsonList.get("total");
        this.totalCount = (int)jsonList.get("totalCount");
        return this;
    }

    public PageRestResultBuilder noLogin() {
        ErrorCode errorCode = GlobalErrorCode.NO_LOGIN;
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
        return this;
    }

    public PageRestResultBuilder failure() {
        this.code = GlobalErrorCode.FAILURE.getCode();
        this.message = GlobalErrorCode.FAILURE.getMessage();
        return this;
    }

    public PageRestResultBuilder message(String message) {
        this.message = message;
        this.code = GlobalErrorCode.FAILURE.getCode();
        return this;
    }


    public PageRestResultBuilder errorCode(ErrorCode errorCode) {
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
        return this;
    }

    @Override
    public PageRestResult build() {
        PageRestResult pageRestResult = new PageRestResult(this.code, this.message, this.data);
        pageRestResult.setStart(this.start);
        pageRestResult.setLimit(this.limit);
        pageRestResult.setTotal(this.total);
        pageRestResult.setTotalCount(this.totalCount);

        return pageRestResult;
    }
}
